import { Component, OnInit, ViewChild, ElementRef, ApplicationRef, NgZone, ChangeDetectorRef } from '@angular/core';
import * as MarkdownIt from 'markdown-it'
import { MdService } from '../../service/md.service';
// import { remote, ipcRenderer } from 'electron';
import { ElectronService } from 'ngx-electron';

declare var MathJax:any
// declare var fs: any; 
// declare const window: any;
// const { ipcRenderer} = window.require('electron');
// then you can continue what you want to do with ipcRenderer.
@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})
export class EditorComponent implements OnInit {

  srcTxt: string = "123"
  title: string = ""
  outTxt: string = ""
  @ViewChild('ta') ta: ElementRef;
  constructor(private ar: ApplicationRef, private zone: NgZone, private cdr: ChangeDetectorRef, private es: ElectronService, private mdSvc: MdService) {
    // ipcRenderer.on('save-to-server', this.doSave.bind(this));
    console.log(this.es)
    console.log(this.es.isElectronApp)
    if (this.es.isElectronApp) {
      this.es.ipcRenderer.on('save-to-server', this.doSave.bind(this));
      this.es.ipcRenderer.on('selected-file', this.onFileSelected.bind(this))
      this.es.ipcRenderer.on('to-save-file', this.saveLocally.bind(this))
    }
      window['mdEditor'] = { component: this, zone: zone };
  }

  doSave() {
    // alert("dosave")
    // this.mdSvc.save(null, this.title, this.srcTxt).subscribe(data=> {
    //   alert("保存成功")
    // }, err => {
    //   alert("保存失败")
    // })
  }
  ngOnInit() {
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
  }

  /**
   * 监测Markdown源码的变化
   * @param  
   */
  srcChanged($event) {
    var md = new MarkdownIt();
    this.outTxt = md.render($event)
  }
  openFile() {
    console.log("openfile")
    this.es.ipcRenderer.send("open-file-dlg")
  }

  onFileSelected(event, files) {
    let that = window['mdEditor'].component;
    let zone = window['mdEditor'].zone;
    zone.run(() => {
      that.srcTxt = files;
    })
  }

  saveLocally() {
    this.es.ipcRenderer.send("save-file", this.srcTxt);
  }
}
